package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.Device;
import com.ny.mapper.DeviceRepository;
import com.ny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/devices")
public class DeviceController {
    
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceRepository deviceRepository;
    
    /**
     * 查询所有设备信息
     * URL: http://127.0.0.1:8081/devices
     * Method: GET
     */
    @GetMapping
    public Result findAllDevices() {
        try {
            List<Device> devices = deviceService.findAllDevices();
            return Result.success(devices);
        } catch (Exception e) {
            return Result.error("查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据设备名称查询设备信息
     * URL: http://127.0.0.1:8081/devices/search?deviceName=空调
     * Method: GET
     */
    @GetMapping("/search")
    public Result findDevicesByName(@RequestParam String deviceName) {
        try {
            // 添加调试信息
            System.out.println("Controller searching for devices with name containing: " + deviceName);
            List<Device> devices = deviceService.findDevicesByName(deviceName);
            System.out.println("Controller found " + devices.size() + " devices");
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加一个直接访问所有设备的接口（从MySQL数据库）
     * URL: http://127.0.0.1:8081/devices/findAll
     * Method: GET
     */
    @GetMapping("/findAll")
    public Result findAllFromMySQL() {
        try {
            List<Device> devices = deviceService.findAllDevices();
            return Result.success(devices);
        } catch (Exception e) {
            return Result.error("查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加一个直接访问所有设备的接口（从MongoDB数据库）
     * URL: http://127.0.0.1:8081/devices/findAllMongo
     * Method: GET
     */
    @GetMapping("/findAllMongo")
    public Result findAllFromMongo() {
        try {
            List<Device> devices = deviceService.findAll();
            return Result.success(devices);
        } catch (Exception e) {
            return Result.error("查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 简化版的根据设备名称查询设备信息
     * URL: http://127.0.0.1:8081/devices/findByName?name=空调
     * Method: GET
     */
    @GetMapping("/findByName")
    public Result findByName(@RequestParam("name") String name) {
        try {
            System.out.println("Finding devices with name containing: " + name);
            List<Device> devices = deviceService.findDevicesByName(name);
            System.out.println("Found " + devices.size() + " devices");
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试数据库连接和查询
     * URL: http://127.0.0.1:8081/devices/test
     * Method: GET
     */
    @GetMapping("/test")
    public Result testDatabase() {
        try {
            System.out.println("Testing database connection and query");
            List<Device> allDevices = deviceService.findAllDevices();
            System.out.println("Total devices in database: " + allDevices.size());
            
            // 测试特定查询
            List<Device> airConditioners = deviceService.findDevicesByName("空调");
            System.out.println("Air conditioners found: " + airConditioners.size());
            
            List<Device> sensors = deviceService.findDevicesByName("传感器");
            System.out.println("Sensors found: " + sensors.size());
            
            return Result.success("Total: " + allDevices.size() + 
                                ", AC: " + airConditioners.size() + 
                                ", Sensors: " + sensors.size());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("测试失败: " + e.getMessage());
        }
    }
    
    /**
     * 专门查询空调设备
     * URL: http://127.0.0.1:8081/devices/airConditioners
     * Method: GET
     */
    @GetMapping("/airConditioners")
    public Result findAirConditioners() {
        try {
            System.out.println("Finding all air conditioners");
            List<Device> devices = deviceService.findAirConditioners();
            System.out.println("Found " + devices.size() + " air conditioners");
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询空调设备失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据设备名称从MongoDB中查询设备
     * URL: http://127.0.0.1:8081/devices/findByNameInMongo?name=空调
     * Method: GET
     */
    @GetMapping("/findByNameInMongo")
    public Result findByNameInMongo(@RequestParam("name") String name) {
        try {
            System.out.println("Finding devices in MongoDB with name: " + name);
            List<Device> devices = deviceService.findDevicesByNameInMongo(name);
            System.out.println("Found " + devices.size() + " devices in MongoDB");
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("从MongoDB查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据设备名称模糊查询MongoDB中的设备
     * URL: http://127.0.0.1:8081/devices/findByNameContainingInMongo?name=空调
     * Method: GET
     */
    @GetMapping("/findByNameContainingInMongo")
    public Result findByNameContainingInMongo(@RequestParam("name") String name) {
        try {
            System.out.println("Finding devices in MongoDB containing name: " + name);
            List<Device> devices = deviceService.findDevicesByNameContainingInMongo(name);
            System.out.println("Found " + devices.size() + " devices in MongoDB");
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("从MongoDB模糊查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据设备名称从MongoDB中查询单个设备
     * URL: http://127.0.0.1:8081/devices/findOneByNameInMongo?name=客厅主灯
     * Method: GET
     */
    @GetMapping("/findOneByNameInMongo")
    public Result findOneByNameInMongo(@RequestParam("name") String name) {
        try {
            System.out.println("Finding one device in MongoDB with name: " + name);
            return deviceService.findOneDeviceByNameInMongo(name)
                    .map(device -> {
                        System.out.println("Found device in MongoDB: " + device.getDeviceName());
                        return Result.success(device);
                    })
                    .orElseGet(() -> {
                        System.out.println("Device not found in MongoDB with name: " + name);
                        return Result.error("设备不存在：" + name);
                    });
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("从MongoDB查询单个设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据状态查询MongoDB中的设备
     * URL: http://127.0.0.1:8081/devices/findByStatus?status=0
     * Method: GET
     */
    @GetMapping("/findByStatus")
    public Result findByStatus(@RequestParam("status") Integer status) {
        try {
            System.out.println("Finding devices in MongoDB with status: " + status);
            List<Device> devices = deviceService.findDevicesByStatus(status);
            System.out.println("Found " + devices.size() + " devices in MongoDB with status " + status);
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("从MongoDB查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据状态和时间范围查询MongoDB中的设备
     * URL: http://127.0.0.1:8081/devices/findByStatusAndTimeRange?status=0&startTime=2023-01-01T00:00:00&endTime=2023-12-31T23:59:59
     * Method: GET
     */
    @GetMapping("/findByStatusAndTimeRange")
    public Result findByStatusAndTimeRange(
            @RequestParam("status") Integer status,
            @RequestParam("startTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date startTime,
            @RequestParam("endTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date endTime) {
        try {
            System.out.println("Finding devices in MongoDB with status: " + status + 
                              " between " + startTime + " and " + endTime);
            List<Device> devices = deviceService.findDevicesByStatusAndTimeRange(status, startTime, endTime);
            System.out.println("Found " + devices.size() + " devices in MongoDB");
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("从MongoDB查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据时间范围查询MongoDB中的设备
     * URL: http://127.0.0.1:8081/devices/findByTimeRange?startTime=2023-01-01T00:00:00&endTime=2023-12-31T23:59:59
     * Method: GET
     */
    @GetMapping("/findByTimeRange")
    public Result findByTimeRange(
            @RequestParam("startTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date startTime,
            @RequestParam("endTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date endTime) {
        try {
            System.out.println("Finding devices in MongoDB between " + startTime + " and " + endTime);
            List<Device> devices = deviceService.findDevicesByTimeRange(startTime, endTime);
            System.out.println("Found " + devices.size() + " devices in MongoDB");
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("从MongoDB查询设备信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查MongoDB中的所有设备数据
     * URL: http://127.0.0.1:8081/devices/debug
     * Method: GET
     */
    @GetMapping("/debug")
    public Result debugMongoData() {
        try {
            System.out.println("Debugging MongoDB data");
            List<Device> allDevices = deviceRepository.findAll();
            System.out.println("Total devices in MongoDB: " + allDevices.size());
            
            // 打印每个设备的详细信息
            for (Device device : allDevices) {
                System.out.println("Device ID: " + device.getDeviceId() + 
                                  ", Name: " + device.getDeviceName() + 
                                  ", Status: " + device.getStatus() + 
                                  ", Created Time: " + device.getCreatedTime());
            }
            
            return Result.success(allDevices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("调试MongoDB数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据设备ID删除MongoDB中的设备
     * URL: http://127.0.0.1:8081/devices/deleteById?deviceId=1
     * Method: DELETE
     */
    @DeleteMapping("/deleteById")
    public Result deleteById(@RequestParam("deviceId") Integer deviceId) {
        try {
            System.out.println("Deleting device with ID: " + deviceId);
            deviceService.deleteDeviceById(deviceId);
            return Result.success("设备删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除设备失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据设备ID查询MongoDB中的设备
     * URL: http://127.0.0.1:8081/devices/findById?deviceId=1
     * Method: GET
     */
    @GetMapping("/findById")
    public Result findById(@RequestParam("deviceId") Integer deviceId) {
        try {
            System.out.println("Finding devices with ID: " + deviceId);
            List<Device> devices = deviceService.findDevicesById(deviceId);
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询设备失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加设备
     * URL: http://127.0.0.1:8081/devices
     * Method: POST
     */
    @PostMapping("")
    public Result addDevice(@RequestBody Device device) {
        try {
            System.out.println("Adding device: " + device.getDeviceName());
            int result = deviceService.addDevice(device);
            if (result > 0) {
                return Result.success("设备添加成功");
            } else {
                return Result.error("设备添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("设备添加失败: " + e.getMessage());
        }
    }
}